import React, { Component } from 'react'
import "./GoodsDetail.scss"
import { Carousel, Toast } from "antd-mobile";
import { imgURL as baseImgPath } from "../../baseURL/baseURL"
import { getGoodsDetailData, getGoodsDislike, getGoodsLike, getGoodsIfLike, getGoodsAdd, getGoodsCartNum } from "../../data/api"
class GoodsDetail extends Component {
  state = {
    goodsDetail: {},
    imgHeight: 176,
    cart: '',
    disappear: "",
    value: 1,
    like: "",
    addInfoAppear: '',
    num: 0,
    sku: '',
    type: [0, 0],
    chooseType: '',
    chooseColor: '',
    choosePlease: '请选择',
    typeName: '',
    colorName: '',
    skuid: 0,
    price: 0,
    stock: 0
  }

  /* 用到的各种方法 */
  //1.点击查看商品评论
  handleComment = () => {
    Toast.info('敬请期待')
  }
  //2.点击主页
  handleHome = () => {
    this.props.history.push('home')
  }
  //3.点击喜欢
  handleLike = async () => {
    let token = localStorage.getItem('token')
    if (token) {
      let goodId = this.props.location.search.split('?')[1]
      if (this.state.like === "like") {
        this.setState({
          like: ""
        })
        await getGoodsDislike(goodId)
      } else {
        this.setState({
          like: "like"
        })
        await getGoodsLike(goodId)
      }
    } else {
      this.props.history.push('login')
    }
  }
  //4.点击购物车
  handleCart = () => {
    this.props.history.push('cart')
  }
  //5.点击立即购买
  handleBuy = () => {
    this.setState({
      cart: "appear",
      disappear: "disappear"
    })
  }
  //6.购物车弹出框点击×关掉
  handleClose = () => {
    this.setState({
      cart: "",
      disappear: ""
    })
  }
  //7.表单受控
  handleInput = (event) => {
    this.setState({ value: event.target.value.trim() - 0 });
  }
  //8.点击"-"数量减少
  handlesub = () => {
    if (this.state.value > 1) {
      this.setState({ value: this.state.value - 1 });
    }
  }
  //9.点击"+"数量增加
  handleadd = () => {
    if (this.state.value < (this.state.goodsDetail && this.state.goodsDetail.goods && this.state.goodsDetail.goods.stock && this.state.goodsDetail.goods.stock - 0)) {
      this.setState({ value: this.state.value + 1 });
    }
  }
  //10.点击购物车弹出框中的立即购买
  handleBuyNow = async () => {
    let token = localStorage.getItem('token')
    if (token) {
      if ((this.state.typeName !== '' && this.state.colorName !== '') || this.state.longer === '') {
        let id = this.state.goodsDetail.goods.id - 0
        let num = this.state.value - 0
        let sku = null
        if (this.state.sku === '') {
          sku = ""
          await getGoodsAdd(num, id, sku)
          let res2 = await getGoodsCartNum()
          let num1 = res2.data.length;
          await this.setState({
            num: num1
          })
        } else {
          sku = this.state.skuid
          await getGoodsAdd(num, id, sku)
          let res2 = await getGoodsCartNum()
          let num1 = res2.data.length;
          await this.setState({
            num: num1
          })
        }
        this.props.history.push('cart')
      } else {
        Toast.info('请先选择商品规格', 1.5)
      }

    } else {
      this.props.history.push('login')
    }
  }
  //11.点击购物车弹出框中的加入购物车
  handleaddgood = async () => {
    let token = localStorage.getItem('token')
    if (token) {
      if ((this.state.typeName !== '' && this.state.colorName !== '') || this.state.longer === '') {
        let id = this.state.goodsDetail.goods.id - 0
        let num = this.state.value - 0
        let sku = null
        if (this.state.sku === '') {
          sku = ""
          await getGoodsAdd(num, id, sku)
          let res2 = await getGoodsCartNum()
          let num1 = res2.data.length;
          await this.setState({
            num: num1
          })
        } else {
          sku = this.state.skuid
          await getGoodsAdd(num, id, sku)
          let res2 = await getGoodsCartNum()
          let num1 = res2.data.length;
          await this.setState({
            num: num1
          })
        }
        let time = null
        if (time) {
          clearTimeout(time)
        }
        this.setState({
          cart: '',
          disappear: '',
          addInfoAppear: 'addInfoAppear'
        })
        let that = this
        time = setTimeout(function () {
          that.setState({
            addInfoAppear: ''
          })
        }, 1000)
      } else {
        Toast.info('请先选择商品规格', 1.5)
      }

    } else {
      this.props.history.push('login')
    }
  }
  //12.购物车弹出时,点其他位置可以收回购物车
  handleBg = () => {
    this.setState({
      cart: "",
      disappear: ""
    })
  }
  //13.点击弹出框中版本或规格
  handleType = async (index, name) => {
    if (index === 1 || index === 2) {
      let num = this.state.type[1]
      if (this.state.type[0] !== index) {
        if (this.state.colorName === "" && this.state.typeName !== "") {
          await this.setState({
            chooseType: '',
            chooseColor: '颜色',
            type: [index, num],
            typeName: name,
          })

        } else if (this.state.colorName !== "" && this.state.typeName === "") {
          await this.setState({
            chooseType: name,
            chooseColor: this.state.colorName,
            type: [index, num],
            choosePlease: '已选择',
            typeName: name,
          })
          if (this.state.type[0] === 1 && this.state.type[1] === 3) {
            await this.setState({
              skuid: 1,
              price: (this.state.goodsDetail.sku.list[0].price / 100).toFixed(2),
              stock: this.state.goodsDetail.sku.list[0].stock_num
            })
          } else if (this.state.type[0] === 1 && this.state.type[1] === 4) {
            await this.setState({
              skuid: 2,
              price: (this.state.goodsDetail.sku.list[1].price / 100).toFixed(2),
              stock: this.state.goodsDetail.sku.list[1].stock_num
            })
          } else if (this.state.type[0] === 2 && this.state.type[1] === 3) {
            await this.setState({
              skuid: 3,
              price: (this.state.goodsDetail.sku.list[2].price / 100).toFixed(2),
              stock: this.state.goodsDetail.sku.list[2].stock_num
            })
          } else if (this.state.type[0] === 2 && this.state.type[1] === 4) {
            await this.setState({
              skuid: 4,
              price: (this.state.goodsDetail.sku.list[3].price / 100).toFixed(2),
              stock: this.state.goodsDetail.sku.list[3].stock_num
            })
          }
        } else if (this.state.colorName === "" && this.state.typeName === "") {
          await this.setState({
            chooseType: '',
            chooseColor: '颜色',
            type: [index, num],
            typeName: name,
          })

        } else if (this.state.colorName !== "" && this.state.typeName !== "") {
          await this.setState({
            chooseType: name,
            chooseColor: this.state.colorName,
            type: [index, num],
            choosePlease: '已选择',
            typeName: name,
          })
          if (this.state.type[0] === 1 && this.state.type[1] === 3) {
            await this.setState({
              skuid: 1,
              price: (this.state.goodsDetail.sku.list[0].price / 100).toFixed(2),
              stock: this.state.goodsDetail.sku.list[0].stock_num
            })
          } else if (this.state.type[0] === 1 && this.state.type[1] === 4) {
            await this.setState({
              skuid: 2,
              price: (this.state.goodsDetail.sku.list[1].price / 100).toFixed(2),
              stock: this.state.goodsDetail.sku.list[1].stock_num
            })
          } else if (this.state.type[0] === 2 && this.state.type[1] === 3) {
            await this.setState({
              skuid: 3,
              price: (this.state.goodsDetail.sku.list[2].price / 100).toFixed(2),
              stock: this.state.goodsDetail.sku.list[2].stock_num
            })
          } else if (this.state.type[0] === 2 && this.state.type[1] === 4) {
            await this.setState({
              skuid: 4,
              price: (this.state.goodsDetail.sku.list[3].price / 100).toFixed(2),
              stock: this.state.goodsDetail.sku.list[3].stock_num
            })
          }
        }
      } else {
        if (this.state.colorName === '') {
          await this.setState({
            type: [0, num],
            typeName: '',
            chooseType: "版本",
            choosePlease: '请选择',
            colorName: this.state.colorName,
            chooseColor: '颜色'
          })
        } else {
          await this.setState({
            type: [0, num],
            typeName: '',
            chooseType: "版本",
            choosePlease: '请选择',
            colorName: this.state.colorName,
            chooseColor: ''
          })
        }
      }
    } else {
      let num = this.state.type[0]
      if (this.state.type[1] !== index) {
        if (this.state.colorName !== "" && this.state.typeName === "") {
          await this.setState({
            chooseType: '版本',
            chooseColor: '',
            type: [num, index],
            colorName: name,
          })

        } else if (this.state.colorName === "" && this.state.typeName !== "") {
          await this.setState({
            chooseColor: name,
            chooseType: this.state.typeName,
            type: [num, index],
            choosePlease: '已选择',
            colorName: name,
          })
          if (this.state.type[0] === 1 && this.state.type[1] === 3) {
            await this.setState({
              skuid: 1,
              price: (this.state.goodsDetail.sku.list[0].price / 100).toFixed(2),
              stock: this.state.goodsDetail.sku.list[0].stock_num
            })
          } else if (this.state.type[0] === 1 && this.state.type[1] === 4) {
            await this.setState({
              skuid: 2,
              price: (this.state.goodsDetail.sku.list[1].price / 100).toFixed(2),
              stock: this.state.goodsDetail.sku.list[1].stock_num
            })
          } else if (this.state.type[0] === 2 && this.state.type[1] === 3) {
            await this.setState({
              skuid: 3,
              price: (this.state.goodsDetail.sku.list[2].price / 100).toFixed(2),
              stock: this.state.goodsDetail.sku.list[2].stock_num
            })
          } else if (this.state.type[0] === 2 && this.state.type[1] === 4) {
            await this.setState({
              skuid: 4,
              price: (this.state.goodsDetail.sku.list[3].price / 100).toFixed(2),
              stock: this.state.goodsDetail.sku.list[3].stock_num
            })
          }
        } else if (this.state.colorName === "" && this.state.typeName === "") {
          await this.setState({
            chooseType: '版本',
            chooseColor: '',
            type: [num, index],
            colorName: name,
          })

        } else if (this.state.colorName !== "" && this.state.typeName !== "") {
          await this.setState({
            chooseType: this.state.typeName,
            chooseColor: name,
            type: [num, index],
            choosePlease: '已选择',
            colorName: name,
          })
          if (this.state.type[0] === 1 && this.state.type[1] === 3) {
            await this.setState({
              skuid: 1,
              price: (this.state.goodsDetail.sku.list[0].price / 100).toFixed(2),
              stock: this.state.goodsDetail.sku.list[0].stock_num
            })
          } else if (this.state.type[0] === 1 && this.state.type[1] === 4) {
            await this.setState({
              skuid: 2,
              price: (this.state.goodsDetail.sku.list[1].price / 100).toFixed(2),
              stock: this.state.goodsDetail.sku.list[1].stock_num
            })
          } else if (this.state.type[0] === 2 && this.state.type[1] === 3) {
            await this.setState({
              skuid: 3,
              price: (this.state.goodsDetail.sku.list[2].price / 100).toFixed(2),
              stock: this.state.goodsDetail.sku.list[2].stock_num
            })
          } else if (this.state.type[0] === 2 && this.state.type[1] === 4) {
            await this.setState({
              skuid: 4,
              price: (this.state.goodsDetail.sku.list[3].price / 100).toFixed(2),
              stock: this.state.goodsDetail.sku.list[3].stock_num
            })
          }
        }

      } else {
        if (this.state.typeName === '') {
          await this.setState({
            type: [num, 0],
            colorName: '',
            chooseColor: '颜色',
            chooseType: '版本',
            typeName: this.state.typeName,
            choosePlease: '请选择',
          })
        } else {
          await this.setState({
            type: [num, 0],
            colorName: '',
            chooseColor: '颜色',
            chooseType: '',
            typeName: this.state.typeName,
            choosePlease: '请选择',
          })
        }


      }
    }
  }

  async componentDidMount() {
    let goodId = this.props.location.search.split('?')[1] - 0
    let token = localStorage.getItem('token')
    if (token) {
      let res2 = await getGoodsCartNum()
      let num = res2.data.length;
      this.setState({
        num: num
      })
      let res1 = await getGoodsIfLike(goodId)
      let ifLike = res1.data
      if (ifLike) {
        this.setState({
          like: "like"
        })
      } else {
        this.setState({
          like: ""
        })
      }
    }
    let res = await getGoodsDetailData(goodId)
    let swiper_list = res.data.goods.gallery.split(',')
    let goodsDetail = res.data
    goodsDetail.goods.gallery = swiper_list
    this.setState({
      goodsDetail: goodsDetail,
      price: (goodsDetail.goods.price / 100).toFixed(2),
      stock: goodsDetail.goods.stock
    })
    if (goodsDetail.sku.list) {
      this.setState({
        longer: 'longer',
        sku: goodsDetail.sku,
        chooseType: goodsDetail.sku.tree[0].k,
        chooseColor: goodsDetail.sku.tree[1].k,
      })
    } else {
      this.setState({
        longer: ''
      })
    }

  }

  render() {
    let DOM = null
    let NUM = null
    if (this.state.longer === "longer") {
      DOM =
        <div className={this.state.cart === "appear" ? "appear gdsCart2" : "gdsCart2"}>
          <div className="goodCartTop">
            <div className="CartTopLeft">
              <img src={this.state.goodsDetail && this.state.goodsDetail.goods && this.state.goodsDetail.goods.pic ? baseImgPath + (this.state.goodsDetail && this.state.goodsDetail.goods && this.state.goodsDetail.goods.pic) : ''} alt="" />
            </div>
            <div className="CartTopCenter">
              <div className="TopCenterPrice">
                ￥{this.state.price}
              </div>
              <div className="TopCenterstock">
                剩余{this.state.stock}件
          </div>
              <div className="TopCenterType">{this.state.choosePlease} {this.state.chooseType} {this.state.chooseColor}</div>
            </div>
            <div className="CartTopRight">
              <i className="iconfont icon-cha" onClick={this.handleClose}></i>
            </div>
          </div>
          <div className="goodCartSpec">
            <div className="CartSpecType">
              {this.state.sku && this.state.sku.tree && this.state.sku.tree.map((val, index) => {
                return (
                  <div className={'cartSpec cartSpec' + val.k_s} key={val.k_s}>
                    <div>{val.k}</div>
                    {val.v.map((value, i) => {
                      let num1 = Math.ceil(value.id / 2)
                      return (
                        <span className={this.state.type[num1 - 1] === value.id ? 'specTypeChoose' : ''} key={value.id} onClick={this.handleType.bind(this, value.id, value.name)}>{value.name}</span>
                      )
                    })}
                  </div>
                )
              })}
            </div>
          </div>
          <div className="goodCartCenter">
            <div className="CartCenterLeft">购买数量</div>
            <div className="CartCenterRight">
              <button className={this.state.value === 1 ? "iconfont icon-jian limitation" : "iconfont icon-jian"} onClick={this.handlesub}></button>
              <input type="text" value={this.state.value} onChange={this.handleInput} />
              <button className={this.state.goodsDetail && this.state.goodsDetail.goods && this.state.goodsDetail.goods.stock && this.state.goodsDetail.goods.stock - 0 === this.state.value ? "iconfont icon-jia limitation" : "iconfont icon-jia"} onClick={this.handleadd}></button>
            </div>
          </div>
          <div className="goodCartBottom">
            <div className="addToCart" onClick={this.handleaddgood}>加入购物车</div>
            <div className="BuyNow" onClick={this.handleBuyNow}>立即购买</div>
          </div>
        </div>
    } else {
      DOM =
        <div className={this.state.cart === "appear" ? "appear gdsCart1" : "gdsCart1"}>
          <div className="goodCartTop">
            <div className="CartTopLeft">
              <img src={this.state.goodsDetail && this.state.goodsDetail.goods && this.state.goodsDetail.goods.pic ? baseImgPath + (this.state.goodsDetail && this.state.goodsDetail.goods && this.state.goodsDetail.goods.pic) : ''} alt="" />
            </div>
            <div className="CartTopCenter">
              <div className="TopCenterPrice">
                ￥{this.state.goodsDetail && this.state.goodsDetail.goods && (this.state.goodsDetail.goods.price / 100).toFixed(2)}
              </div>
              <div className="TopCenterstock">
                剩余{this.state.goodsDetail && this.state.goodsDetail.goods && this.state.goodsDetail.goods.stock}件
          </div>
            </div>
            <div className="CartTopRight">
              <i className="iconfont icon-cha" onClick={this.handleClose}></i>
            </div>
          </div>
          <div className="goodCartCenter">
            <div className="CartCenterLeft">购买数量</div>
            <div className="CartCenterRight">
              <button className={this.state.value === 1 ? "iconfont icon-jian limitation" : "iconfont icon-jian"} onClick={this.handlesub}></button>
              <input type="text" value={this.state.value} onChange={this.handleInput} />
              <button className={this.state.goodsDetail && this.state.goodsDetail.goods && this.state.goodsDetail.goods.stock && this.state.goodsDetail.goods.stock - 0 === this.state.value ? "iconfont icon-jia limitation" : "iconfont icon-jia"} onClick={this.handleadd}></button>
            </div>
          </div>
          <div className="goodCartBottom">
            <div className="addToCart" onClick={this.handleaddgood}>加入购物车</div>
            <div className="BuyNow" onClick={this.handleBuyNow}>立即购买</div>
          </div>
        </div>
    }
    if (this.state.num !== 0) {
      NUM = <div className="cartGoodsNum">{this.state.num === 0 ? "" : this.state.num}</div>
    }
    return (
      /* 商品详情页开始 */
      <div className="goodsDetail">
        {/* 详情页顶部主要内容开始 */}
        <div className="gdsTopContent">

          {/* 详情页轮播图开始 */}
          <div className="goodSwiper">
            <Carousel autoplay dots infinite>
              {(this.state.goodsDetail &&
                this.state.goodsDetail.goods &&
                this.state.goodsDetail.goods.gallery.map((val, index) => (
                  <div
                    className="gdSwiperItem"
                    key={this.state.goodsDetail && this.state.goodsDetail.goods && this.state.goodsDetail.goods.id}
                    style={{
                      display: "inline-block",
                      width: "100%",
                      height: this.state.imgHeight,
                    }}
                  >
                    <img
                      src={val === undefined ? '' : baseImgPath + val}
                      alt=""
                      onLoad={() => {
                        // fire window resize event to change height
                        window.dispatchEvent(new Event("resize"));
                        this.setState({ imgHeight: "auto" });
                      }}
                    />
                  </div>
                ))) || ""}
            </Carousel>
          </div>
          {/* 详情页轮播图结束 */}

          {/* 详情页商品信息开始 */}
          <div className="goodInfo">
            <div className="goodInfoCon">
              {/* 详情页商品描述开始 */}
              <div className="goodInfoDescript">
                <div className="goodInfo-top">
                  {this.state.goodsDetail && this.state.goodsDetail.goods && this.state.goodsDetail.goods.name}
                </div>
                <div className="goodInfo-center">
                  {this.state.goodsDetail && this.state.goodsDetail.goods && this.state.goodsDetail.goods.descript}
                </div>
                <div className="goodInfo-bottom">
                  {this.state.goodsDetail && this.state.goodsDetail.goods && (this.state.goodsDetail.goods.price / 100).toFixed(2)}
                </div>
              </div>
              {/* 详情页商品描述结束 */}

            </div>
            {/* 详情页商品快递和库存开始 */}
            <div className="goodInfoExpress">
              <div className="InfoExpressCon">
                <div className="goodExpressLeft">
                  运费：免运费
                </div>
                <div className="goodExpressCenter">
                  剩余：{this.state.goodsDetail && this.state.goodsDetail.goods && this.state.goodsDetail.goods.stock}
                </div>
              </div>
            </div>
            {/* 详情页商品快递和库存结束 */}

          </div>
          {/* 详情页商品信息结束 */}

          {/* 详情页商品评论开始 */}
          <div className="goodComment" onClick={this.handleComment}>
            <div className="goodCommentCon">
              <span>查看商品评论</span>
              <i className="iconfont icon-youjiankuohao"></i>
            </div>
          </div>
          {/* 详情页商品评论结束 */}

          {/* 详情页商品图片开始 */}
          <div className="goodPics">
            <div
              dangerouslySetInnerHTML={{ __html: this.state.goodsDetail && this.state.goodsDetail.goods && this.state.goodsDetail.goods.detail }}
            ></div>
          </div>
          {/* 详情页商品图片结束 */}
        </div>
        {/* 详情页顶部主要内容结束 */}

        {/* 详情页底部功能栏开始 */}
        <div className="gdsBottomTab">
          <div className="goodBottomTabItem" onClick={this.handleHome}>
            <i className="iconfont icon-shouye"></i>
            <span>主页</span>
          </div>
          <div className="goodBottomTabItem" onClick={this.handleLike}>
            <i className={this.state.like === "like" ? "iconfont icon-xinaixin like" : "iconfont icon-xinaixin"}></i>
            <span>喜欢</span>
          </div>
          <div className="goodBottomTabItem" onClick={this.handleCart}>
            <i className="iconfont icon-gouwuche"></i>
            <span>购物车</span>
            {NUM}
          </div>
          <div className="goodBottomTabItem">
            <div className="TabItemBuyNow" onClick={this.handleBuy}>立即购买</div>
          </div>
        </div>
        {/* 详情页底部功能栏结束 */}

        {/* 详情页点击立即购买弹出开始 */}
        {DOM}
        {/* 详情页点击立即购买弹出结束 */}

        {/* Cart弹出背景变黑开始 */}
        <div className={this.state.disappear === "disappear" ? "gdsCartBg" : "gdsCartBg disappear"} onClick={this.handleBg}></div>
        {/* Cart弹出背景变黑结束 */}

        {/* 点击加入购物车弹出info */}
        <div className={this.state.addInfoAppear === "addInfoAppear" ? "goodaddinfo addInfoAppear" : "goodaddinfo "}>
          <i className="iconfont icon-gouwuche"></i>
          <span>已加入到购物车</span>
        </div>
      </div>
      /* 商品详情页结束 */
    )
  }
}
export default GoodsDetail;